const fs = require('fs');

const {Readable} = require('stream');
const axios = require("axios");

async function saveWithProgress(filename, arrayBuffer) {
    const buffer = Buffer.from(arrayBuffer.buffer, arrayBuffer.byteOffset, arrayBuffer.byteLength);
    const totalBytes = buffer.length;
    let bytesWritten = 0;
    // const totalKib = (totalBytes / 1024).toFixed(2)
    // 创建可读流
    const readable = new Readable({
        read(size) {
            const chunk = buffer.subarray(bytesWritten, bytesWritten + size);
            this.push(chunk.length ? chunk : null);
            bytesWritten += chunk.length;
            // 打印进度
            // const progress = (bytesWritten / totalBytes * 100).toFixed(2);
            // const red = (bytesWritten / 1024).toFixed(2)
            // process.stdout.write(`\r进度: ${progress}% (${red}/${totalKib} kb)`);
        }
    });

    // 创建可写流
    const writable = (await fs.promises.open(filename, 'w')).createWriteStream();
    // writable.write(arrayBuffer)
    // // 管道传输
    readable.pipe(writable);
    //
    return new Promise((resolve, reject) => {
        writable.on('finish', resolve);
        writable.on('error', reject);
    });
}

function downloadBuffer(url, filename,progress) {
    return new Promise(async (resolve, reject) => {
        try {
            const exists = fs.existsSync(filename)
            if (exists) {
                return resolve()
            }
            const {data,headers} = await axios({
                url: url,
                method: 'get',
                // responseType: 'arraybuffer',
                responseType: 'stream', // 使用流式响应
                onDownloadProgress(e) {
                    progress && progress(e)
                }
            })
            const writer = fs.createWriteStream(filename);
            data.pipe(writer); // 将数据流直接写入文件

            let downloaded = 0;

            const total = parseInt(headers['content-length'], 10); // 获取文件总大小

            data.on('data', chunk => {
                if (progress && total) {
                    downloaded += chunk.length;
                    progress({progress:downloaded / total});
                }
            });

            writer.on('finish', () => resolve()); // 写入完成
            writer.on('error', reject); // 写入出错
        } catch (e) {
            reject(e)
        }
    })
}

module.exports = {saveWithProgress, downloadBuffer};
